define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'knowbase'], function ($, undefined, Backend, Table, Form, Knowbase) {

    var Controller = {
        refreshSelect: {
            'auth_group_ids': false,
            'admin_id':false,
        },
        oldData: {
            'auth_group_ids': '',
            'admin_id':'',
        },
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'knowbase/project_page_template/index' + location.search,
                    add_url: 'knowbase/project_page_template/add',
                    edit_url: 'knowbase/project_page_template/edit',
                    del_url: 'knowbase/project_page_template/del',
                    multi_url: 'knowbase/project_page_template/multi',
                    import_url: 'knowbase/project_page_template/import',
                    table: 'knowbase_project_page_template',
                }
            });

            var table = $("#table");

            var buttons = [{
                name: 'edit',
                icon: 'fa fa-pencil',
                title: __('Edit'),
                extend: 'data-toggle="tooltip" data-container="body" data-area=["100%","100%"]',
                classname: 'btn btn-xs btn-success btn-editone'
            }, {
                name: 'del',
                icon: 'fa fa-trash',
                title: __('Del'),
                extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-danger btn-delone',
            }];

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                onClickCell: function (field, value, row, $element) {
                    // 记录原先的选择
                    Controller.oldData.auth_group_ids = $('#c-auth_group_ids').val();
                    if (field == 'auth_group_ids') {
                        Controller.refreshSelect.auth_group_ids = true;
                    } else if (field =='admin_id') {
                        Controller.refreshSelect.admin_id = true;
                    }

                },
                onCommonSearch: function (params) {
                    // 请求前触发
                    if (Controller.refreshSelect.auth_group_ids) {
                        var new_auth_group_ids = $('#c-auth_group_ids').val();
                        var old_auth_group_ids = Controller.oldData.auth_group_ids;
                        if (old_auth_group_ids != '') {
                            old_auth_group_ids = old_auth_group_ids.split(',');
                            old_auth_group_ids.push(new_auth_group_ids);
                            old_auth_group_ids = Knowbase.unique(old_auth_group_ids).join(',');
                        } else {
                            old_auth_group_ids = new_auth_group_ids;
                        }
                        $('#c-auth_group_ids').val(old_auth_group_ids);
                    }

                },
                onRefresh: function (params) {
                    if (Controller.refreshSelect.auth_group_ids) {
                        $('#c-auth_group_ids').selectPageRefresh();
                        Controller.refreshSelect.auth_group_ids = false;
                    }

                    if (Controller.refreshSelect.admin_id){
                        $('#c-admin_id').selectPageRefresh();
                        Controller.refreshSelect.admin_id = false;
                    }

                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'name',
                            title: __('Name'),
                            operate: 'LIKE',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'type',
                            title: __('Type'),
                            searchList: {"0": __('Type 0'), "1": __('Type 1'), "2": __('Type 2')},
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'auth_group_ids',
                            title: __('Auth_group_ids'),
                            operate: "IN",
                            table: table,
                            class: 'autocontent',
                            formatter: Controller.api.formatter.flag,
                            display: function (row, index) {
                                if (row.groups[index] && row.groups[index].auth_group) {
                                    return row.groups[index].auth_group.name;
                                } else {
                                    return '';
                                }
                            },
                            getValue:function (row,index){
                                if (row.groups[index] && row.groups[index].auth_group) {
                                    return row.groups[index].auth_group.id;
                                } else {
                                    return '';
                                }
                            },
                            searchList: function (column) {
                                return '<input id="c-auth_group_ids"  data-source="knowbase/group_new/index" ' +
                                    'data-order-by="id" data-multiple="true" ' +
                                    'data-page-size="20"  ' +
                                    'data-search-field="id" ' +
                                    'data-field="name" ' +
                                    'data-pagination="true" ' +
                                    'class="form-control selectpage" ' +
                                    'name="auth_group_ids" type="text" value="">';
                            }
                        },
                        {
                            field: 'admin_id', title: __('Admin_id'), searchList: function (column) {
                                return '<input id="c-admin_id"  data-source="auth/admin/index" ' +
                                    'data-order-by="id" data-multiple="false" ' +
                                    'data-page-size="20"  ' +
                                    'data-search-field="username" ' +
                                    'data-field="username" ' +
                                    'data-pagination="true" ' +
                                    'class="form-control selectpage" ' +
                                    'name="admin_id" type="text" value="">';
                            },formatter: Controller.api.formatter.normal,display:function (row){
                                return row.admin?row.admin.username:"-";
                            }
                        },
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        templates: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'knowbase/project_page_template/index' + location.search,
                    add_url: 'knowbase/project_page_template/add',
                    edit_url: 'knowbase/project_page_template/edit',
                    table: 'knowbase_project_page_template',
                }
            });

            var table = $("#table");

            var buttons = [{
                name: 'edit',
                icon: 'fa fa-pencil',
                title: __('Edit'),
                extend: 'data-toggle="tooltip" data-container="body" data-area=["100%","100%"]',
                classname: 'btn btn-xs btn-success btn-editone',
                hidden: function (row) {
                    if (Config.is_super_admin==0) {
                        if (row.type==1) {
                            var groups = row.auth_group_ids.split(",");
                            var rs = Knowbase.array_intersection(groups,Config.groups);
                            if (rs.length>0) {
                                return false;
                            }
                            return true;
                        } else if (row.type==2) {
                            if (Config.admin_id==row.admin_id) {
                                return false;
                            }
                            return true;
                        }
                    }
                    return false;
                }
            },{
                name: 'insert',
                icon: 'fa fa-arrow-circle-o-left',
                title: __('btn_insert'),
                extend: 'data-toggle="tooltip" data-container="body" ',
                classname: 'btn btn-xs btn-info btn-insertone'
            }, {
                name: 'del',
                icon: 'fa fa-trash',
                title: __('Del'),
                extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-danger btn-delone',
                hidden: function (row) {
                    return true;
                }
            }];

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                commonSearch: false,
                queryParams: function (params) {
                    var filter = {};
                    var op = {};
                    if (params.filter != undefined) {
                        filter = JSON.parse(params.filter);
                    }
                    if (params.op != undefined) {
                        op = JSON.parse(params.op);
                    }
                    var value = $('.panel-heading .nav-tabs li.active a').attr('data-value');
                    filter.type = value;
                    op.type = "=";
                    params.filter = JSON.stringify(filter);
                    params.op = JSON.stringify(op);
                    return params;
                },
                columns: [
                    [
                        // {checkbox: true},
                        // {field: 'id', title: __('Id')},
                        {
                            field: 'name',
                            title: __('Name'),
                            operate: 'LIKE',
                            align: 'left',
                            table: table,
                            class: 'autocontent',
                            formatter: Table.api.formatter.content
                        },
                        {
                            field: 'type',
                            title: __('Type'),
                            searchList: {"0": __('Type 0'), "1": __('Type 1'), "2": __('Type 2')},
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'admin_id', title: __('Admin_id'), searchList: function (column) {
                                return '<input id="c-admin_id"  data-source="auth/admin/index" ' +
                                    'data-order-by="id" data-multiple="false" ' +
                                    'data-page-size="20"  ' +
                                    'data-search-field="username" ' +
                                    'data-field="username" ' +
                                    'data-pagination="true" ' +
                                    'class="form-control selectpage" ' +
                                    'name="admin_id" type="text" value="">';
                            }, formatter: function (value, row, index) {
                                return row.admin ? row.admin.username : "--";
                            }
                        },
                        // {
                        //     field: 'createtime',
                        //     title: __('Createtime'),
                        //     operate: 'RANGE',
                        //     addclass: 'datetimerange',
                        //     autocomplete: false,
                        //     formatter: Table.api.formatter.datetime
                        // },
                        // {
                        //     field: 'updatetime',
                        //     title: __('Updatetime'),
                        //     operate: 'RANGE',
                        //     addclass: 'datetimerange',
                        //     autocomplete: false,
                        //     formatter: Table.api.formatter.datetime
                        // },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Controller.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: buttons
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // $('a[data-toggle="tab"]').unbind('shown.bs.tab');
            // var cloneQueryParams = null;
            // //绑定TAB事件
            // $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            //
            //     var field = $(this).closest("[data-field]").data("field");
            //     var value = $(this).data("value");
            //     var options = table.bootstrapTable('getOptions');
            //     options.pageNumber =1;
            //     if (cloneQueryParams == null) {
            //         cloneQueryParams = options.queryParams;
            //     }
            //     options.queryParams =function(params){
            //         params.filter = JSON.stringify({type: value});
            //         return cloneQueryParams(params);
            //     };
            //     table.bootstrapTable('refresh',{});
            //     return false;
            // });


        },
        add: function () {
            Controller.api.bindevent();
            this.initListen();
        },
        edit: function () {
            Controller.api.bindevent();
            this.initListen();
        },
        initListen: function () {
            $(document).on("change", "#c-type", function (e) {
                //变更后的回调事件
                var value = $(this).val();
                $('.auth_group_ids').hide();
                if (value == 1) {
                    $('.auth_group_ids').show();
                }
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function () {
                    var eles = $(Config.knowbase.classname || '.vditor_editor');
                    if (eles.length > 0) {
                        for (var i = 0; i < eles.length; i++) {
                            var ele = $(eles[i]);
                            var id = ele.attr('id');
                            if (id && window.vditorlist && window.vditorlist[id]) {
                                // 防止新增出现缓存
                                window.vditorlist[id].clearCache();
                            }
                        }
                    }
                }, function () {
                }, function (success, error) {
                    var eles = $(Config.knowbase.classname || '.vditor_editor');
                    if (eles.length > 0) {
                        for (var i = 0; i < eles.length; i++) {
                            var ele = $(eles[i]);
                            var id = ele.attr('id');
                            if (id && window.vditorlist && window.vditorlist[id]) {
                                $('#' + id.replace('-vditor', '')).val(window.vditorlist[id].getValue());
                            }
                        }
                    }
                    return true;
                });
            },
            formatter: {
                flag: function (value, row, index) {
                    var that = this;
                    value = value == null || value.length === 0 ? '' : value.toString();
                    var colorArr = {index: 'success', hot: 'warning', recommend: 'danger', 'new': 'info'};
                    //如果字段列有定义custom
                    if (typeof this.custom !== 'undefined') {
                        colorArr = $.extend(colorArr, this.custom);
                    }
                    var field = this.field;
                    if (typeof this.customField !== 'undefined' && typeof row[this.customField] !== 'undefined') {
                        value = row[this.customField];
                        field = this.customField;
                    }

                    if (typeof that.searchList === 'object' && typeof that.custom === 'undefined') {
                        var i = 0;
                        var searchValues = Object.values(colorArr);
                        $.each(that.searchList, function (key, val) {
                            if (typeof colorArr[key] == 'undefined') {
                                colorArr[key] = searchValues[i];
                                i = typeof searchValues[i + 1] === 'undefined' ? 0 : i + 1;
                            }
                        });
                    }

                    //渲染Flag
                    var html = [];
                    var arr = value != '' ? value.split(',') : [];
                    var color, display, label;
                    $.each(arr, function (i, value) {
                        value = value == null || value.length === 0 ? '' : value.toString();
                        if (value == '')
                            return true;
                        color = value && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                        display = typeof that.searchList !== 'undefined' && typeof that.searchList[value] !== 'undefined' ? that.searchList[value] : __(value.charAt(0).toUpperCase() + value.slice(1));
                        if (typeof that.display === 'function') {
                            display = that.display(row, i);
                            if (display == '') {
                                return true;
                            }
                        }

                        if (typeof that.getValue === 'function') {
                            value = that.getValue(row,i);
                        }

                        label = '<span class="label label-' + color + '">' + display + '</span>';
                        if (that.operate) {
                            html.push('<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + field + '" data-value="' + value + '">' + label + '</a>');
                        } else {
                            html.push(label);
                        }
                    });
                    return html.join(' ');
                },
                normal:function (value, row, i) {
                    var that = this;
                    var colorArr = ["primary", "success", "danger", "warning", "info", "gray", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];
                    var custom = {};
                    if (typeof this.custom !== 'undefined') {
                        custom = $.extend(custom, this.custom);
                    }
                    value = value == null || value.length === 0 ? '' : value.toString();
                    var keys = typeof this.searchList === 'object' ? Object.keys(this.searchList) : [];
                    var index = keys.indexOf(value);
                    var color = value && typeof custom[value] !== 'undefined' ? custom[value] : null;
                    var display = index > -1 ? this.searchList[value] : null;
                    var icon = typeof this.icon !== 'undefined' ? this.icon : null;
                    if (!color) {
                        color = index > -1 && typeof colorArr[index] !== 'undefined' ? colorArr[index] : 'primary';
                    }

                    if (!display) {
                        display = __(value.charAt(0).toUpperCase() + value.slice(1));
                    }
                    if (typeof that.display === 'function') {
                        display = that.display(row);
                        if (display=='-') {
                            return '-';
                        }
                    }
                    var html = '<span class="text-' + color + '">' + (icon ? '<i class="' + icon + '"></i> ' : '') + display + '</span>';
                    if (this.operate != false) {
                        html = '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + this.field + '" data-value="' + value + '">' + html + '</a>';
                    }
                    return html;
                }
            },
            events:{
                operate:{
                    'click .btn-editone': function (e, value, row, index) {
                        e.stopPropagation();
                        e.preventDefault();
                        var table = $(this).closest('table');
                        var options = table.bootstrapTable('getOptions');
                        var ids = row[options.pk];
                        row = $.extend({}, row ? row : {}, {ids: ids});
                        var url = options.extend.edit_url;
                        parent.parent.Fast.api.open(Table.api.replaceurl(url, row, table), $(this).data("original-title") || $(this).attr("title") || __('Edit'), $(this).data() || {});
                    },
                    'click .btn-insertone': function (e, value, row, index) {
                        e.stopPropagation();
                        e.preventDefault();
                        // 往父容器添加模板代码
                        parent.insertTemplate(row.content,'c-content-vditor');
                    }
                }
            }
        }
    };
    return Controller;
});
